from tortoise.expressions import Q

from app.controllers.goods.sku import sku_controller
from app.core.crud import CRUDBase
from app.models.orders import OrdersCar
from app.schemas.orders import OrdersCarCreate,OrdersCarUpdate
from app.models.goods import GoodsSku


class OrdersCarController(CRUDBase[OrdersCar, OrdersCarCreate, OrdersCarUpdate]):
    def __init__(self):
        super().__init__(model=OrdersCar)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at","deleted_at"]) for obj in objs]
        return total, data

    async def do_create(self, obj_in: OrdersCarCreate):
        await self.create(obj_in=obj_in)
        return True

    async def do_update(self, obj_in: OrdersCarUpdate):
        sku_data = await GoodsSku.filter(id=obj_in.sku_id).first().values("sku_level","sku_kc")
        sku_level = sku_data['sku_level']
        sku_kc = sku_data['sku_kc']
        obj_in.price = sku_level[1] * obj_in.num
        if sku_kc<obj_in.num:
            return False
        else:
            await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self,search: Q = Q()):
        await self.remove_q(search)
        return True

    async def do_delete_admin(self, data_id: int):
        await self.remove(id=data_id)
        return True


orders_car_controller = OrdersCarController()
